import Vue from 'vue'
import Router from 'vue-router'
import draggable from '@/components/index'
import newDraggable from '@/components/draggable'
Vue.use(Router)

const router = new Router({
  base: 'vueElementAdmin',
  routes: [
    // {
    //   path: '/',
    //   name: 'Admin',
    //   component: resolve => require(['@/pages/admin'], resolve),
    //   children: [
    //     ...demo,
    //     ...menu,
    //   ]
    // },
    {
      path: '/',
      name: 'index',
      component: resolve => require(['@/pages/index'], resolve),
      children: [
        {
          path: '/indexForm',
          name: 'newForm',
          component: resolve => require(['@/pages/newDraggable/form'], resolve)
        },
        {
          path: '/diyForm',
          name: 'diyForm',
          component: resolve => require(['@/pages/DiyForm/index'], resolve)
        },
        {
          path: '/table',
          name: 'table',
          component: resolve => require(['@/pages/table/diyTable'], resolve)
        },
      ]
    },
    {
      path: '/draggable',
      name: 'draggable',
      component: draggable
    },

    {
      path: '/newDraggable',
      name: 'newDraggable',
      component: newDraggable
    },
    {
      path: '/404',
      name: '404',
      component: resolve => require(['@/pages/error-page/404'], resolve)
    },
    {
      path: '/login',
      name: 'Login',
      component: resolve => require(['@/pages/login/login'], resolve)
    }
  ]
})
router.beforeEach((to, from, next) => {
  let that = router.app;
  //获取本地的token
  const token = localStorage.getItem("token");
  //是否是个人中心页面
  const patharr = ['/'];
  //这里通过indexOf来检验to.path有没有admin页面
  if (patharr.indexOf(to.path) > -1) {
    if (token) {
      return next();
    } else {
      return router.push({
        path: '/login'
      }).catch(err => {
        //这里catch捕获了错误，在前端就不会显示了
        console.log(err)
      });
    }
  } else {
    //这里有个保底的操作,其他页面直接放行
    next();
  }
  //防止报错 Avoided redundant navigation to current location: "/partyManage/party/list" ---重复路由的问题
  const originalPush = Router.prototype.push
  Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
  }

  const originalReplace = Router.prototype.replace;
  Router.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err);
  }
  if (to.matched.length === 0) {
    //如果未匹配到路由
    next({ path: '/404' });
    that.$message({ type: 'error', message: '正在建设中.....' });
  } else if (to.name === 'Login') {
    //正常进入登录页，不做token验证
    next();

  } else {
    if (!localStorage.getItem("token")) {
      //如果token不存在跳登录页
      that.$message({ type: 'error', message: '请登录系统....' });
      next({ path: '/login?page=' });
    } else {

      next();
    }
  }

})
export default router;